//
//  SettingViewController.m
//  VoiceClass
//
//  Created by caoxiaobo on 2018/1/7.
//  Copyright © 2018年 YRX. All rights reserved.
//

#import "SettingViewController.h"
#import "BrowseResultViewController.h"
#import "IAMetaDataReader.h"
#import "MBProgressHUD.h"

static NSString * const settingCellID = @"settingCellID";

@interface SettingViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    
    _tableView = [[UITableView alloc] init];
    _tableView.frame = self.view.bounds;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.rowHeight = 56.0f;
    [self.view addSubview:_tableView];
}

- (void)close {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:settingCellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:settingCellID];
    }
    if (indexPath.row == 0) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = @"查看全部答题数据";
        
    } else if (indexPath.row == 1) {
        cell.textLabel.text = @"清除所有答题数据";
        long long size = [IAMetaDataReader getAllSubjectResultsBytes];
        NSString *sizeString = @"";
        if (size > 1024) {
            sizeString = [NSString stringWithFormat:@"%0.2fM", size / 1024.0];
        } else {
            sizeString = [NSString stringWithFormat:@"%0.2fk", (float)size];
        }
        cell.detailTextLabel.text = sizeString;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        [IAMetaDataReader getAllSubjectResultsWithCompletion:^(id obj) {
            BrowseResultViewController *browseController = [[BrowseResultViewController alloc] initWithSubjectResults:obj];
            [self.navigationController pushViewController:browseController animated:YES];
        }];
    } else if (indexPath.row == 1) {
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
        [hud showAnimated:YES];
        [IAMetaDataReader removeAllSubjectResultsBytesWithCompletion:^(BOOL result) {
            [hud hideAnimated:YES];
            [self.tableView reloadData];
        }];
    }
}

@end
